package org.light.facade;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.javaforever.gatescore.core.FrontProject;
import org.javaforever.gatescore.generators.PackageJsonGenerator;
import org.light.compiler.SGSCompiler;
import org.light.domain.Project;
import org.light.domain.ValidateInfo;
import org.light.exception.ValidateException;

import net.sf.json.JSONObject;

/**
 * Servlet implementation class GenerateSampleCodeController
 */

public class GenerateSampleCodeFacade extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GenerateSampleCodeFacade() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	
	 protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 response.setContentType("application/json;charset=UTF-8");
          		  	PrintWriter out = response.getWriter();
		 Map<String,Object> result = new TreeMap<String,Object>();
		 try {			
			String sourcefolder = request.getSession().getServletContext().getRealPath("/")+"source/";
			sourcefolder = sourcefolder.replace('\\', '/');
			
			String sgscode = request.getParameter("code");
			String ignoreWarning = request.getParameter("ignoreWarning");
			boolean ignoreWarningBoolean = ignoreWarning == null || ignoreWarning.equals("")?false:Boolean.parseBoolean(ignoreWarning);
			
			String root = request.getSession().getServletContext().getRealPath("/").replace('\\', '/');
			String generateFront = request.getParameter("generateFront");
			String useUserPartial = request.getParameter("useUserPartial");
			String exportStr =request.getParameter("exportStr");
			
			String genFormatted = request.getParameter("genFormatted");

			String autoConfig = request.getParameter("autoConfig");
			String frontUseProjectName = request.getParameter("frontUseProjectName");
			String frontUseControllerPrefix = request.getParameter("frontUseControllerPrefix");
			String sqlComments = request.getParameter("sqlComments");
			String generateExcel = request.getParameter("generateExcel");
			String goCompatibility = request.getParameter("goCompatibility");
			String rustCompatibility = request.getParameter("rustCompatibility");
			
			String useAdvancedCustomize = request.getParameter("useAdvancedCustomize");
			String genUiStr = request.getParameter("genUi");
			String genControllerStr = request.getParameter("genController");
			String genServiceStr = request.getParameter("genService");
			String genServiceImplStr = request.getParameter("genServiceImpl");
			String genDaoStr = request.getParameter("genDao");
			String genDaoImplStr = request.getParameter("genDaoImpl");
			
			boolean genUi = true;
			boolean genController=true;
			boolean genService = true;
			boolean genServiceImpl = true;
			boolean genDao = true;
			boolean genDaoImpl = true;
			if ("true".equalsIgnoreCase(useAdvancedCustomize)) {
				genUi = "true".equalsIgnoreCase(genUiStr);
				genController = "true".equalsIgnoreCase(genControllerStr);
				genService = "true".equalsIgnoreCase(genServiceStr);
				genServiceImpl = "true".equalsIgnoreCase(genServiceImplStr);
				genDao = "true".equalsIgnoreCase(genDaoStr);
				genDaoImpl = "true".equalsIgnoreCase(genDaoImplStr);
			}
			
			if ("false".equalsIgnoreCase(useUserPartial)) {
				exportStr = "";
			}
			
			System.out.println(sgscode);
			Project project = SGSCompiler.translate(sgscode,ignoreWarningBoolean);
			
			System.out.println(sourcefolder);
			project.setFolderPath(sourcefolder);
			project.setSourceFolderPath((request.getSession().getServletContext().getRealPath("/")+"templates/").replace('\\', '/'));
			project.setModuleSourceFolderPath((request.getSession().getServletContext().getRealPath("/")+"moduletemplates/").replace('\\', '/'));
			project.generateProjectZip(ignoreWarningBoolean,"true".equalsIgnoreCase(genFormatted),genUi,genController,genService,genServiceImpl,genDao,genDaoImpl,"true".equalsIgnoreCase(generateExcel),exportStr);			

			FrontProject frontend = null;
			if ("true".equalsIgnoreCase(generateFront)) {
				frontend = org.javaforever.gatescore.compiler.SGSCompiler.translate(sgscode, true);
				frontend.setTemplatesPath(root+"templates/");
				frontend.setFolderPath(root+"source/");
				frontend.setProjectHome("https://gitee.com/jerryshensjf/InfinityJEEEU/");
				frontend.setBackendProjectName(project.getStandardName());
				frontend.setStandardName(project.getStandardName()+"FrontEnd");		
				frontend.setShowBackendProject("true".equals(frontUseProjectName));
				frontend.setUseController(true);
				frontend.setUseControllerPrefix("true".equals(frontUseControllerPrefix));
				frontend.setComputerLanguage("java");
				frontend.setTechnicalstack("mjeeeu");
				frontend.setPjg(new PackageJsonGenerator(frontend.getDomains().get(0)));
				frontend.generateProjectZip(exportStr);
			}
			
			result.put("success", true);
			result.put("projectName", project.getStandardName());
			if (frontend !=null) result.put("frontProjectName", frontend.getStandardName());
			
			out.print(JSONObject.fromObject(result));
		 } catch (ValidateException ev){
			result.put("success", false);
			ValidateInfo info = ev.getValidateInfo();
			List<String> compileErrors = info.getCompileErrors();
			result.put("compileErrors", compileErrors);
			List<String> compileWarnings = info.getCompileWarnings();
			result.put("compileWarnings", compileWarnings);
			out.print(JSONObject.fromObject(result));
		 }catch(Exception e){
			if (!(e instanceof ValidateException)) {
				e.printStackTrace();
				result.put("success", false);
				if (e.getMessage() != null && !e.getMessage().equals("")){
					result.put("reason", e.getMessage());
				}else {
					result.put("reason", "Null pointer or other syntax error.");
				}
				out.print(JSONObject.fromObject(result));
			}
		}finally{
			out.close();
		}
	 }

}
